<template>
  <div class="container-fluid" style="background: #fff">
    <div class="row page-title">
        <div class="col-xs-11">
            <h1>{{$route.query.type==1?'多视频':'单视频'}}</h1>
        </div>
    </div>
    <el-form label-width="150px" :model="form" ref="form" :rules="rules">
      <el-col :span="24">
          <el-form-item label="预览图：">
              <el-upload
                  class="avatar-uploader"
                  :action="uploadUrl"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
              </el-upload>
              <i class="el-text-danger el-icon-circle-close" v-if="!imageUrl"></i>
              <span v-if="imageUrl">上传成功&nbsp;&nbsp;&nbsp;&nbsp;<i class="text-success el-icon-circle-check"></i></span>
              <a :href="form.ShowImage" target="_blank">查看图片</a>
          </el-form-item>
      </el-col>
    <el-col :span="24" style="width:30%">
        <el-form-item label="标题：" prop="Title">
            <el-input v-model="form.Title"></el-input>
        </el-form-item>
    </el-col>
      <el-col :span="20">
          <el-form-item label="描述：" prop="Diction">
              <el-input type="textarea" v-model="form.Diction"></el-input>
          </el-form-item>
      </el-col>
      <el-col :span="8">
          <el-form-item label="金币价格：" prop="GoldPrice">
              <el-input v-model="form.GoldPrice"></el-input>
          </el-form-item>
      </el-col>
      <el-col :span="8" :offset="4">
          <el-form-item label="主讲专家：" prop="ExpertId">
                <el-select v-model="form.ExpertId" filterable remote reserve-keyword placeholder="请输入关键词" :remote-method="remoteMethod" :loading="loading" clearable style="width:100%">
                    <el-option v-for="item in searchedSelectList" :key="item.ExpertId" :label="item.ExpertName" :value="item.ExpertId"></el-option>
                </el-select>
          </el-form-item>
      </el-col>
      <el-col :span="20" v-if="$route.query.type!==1">
          <el-form-item label="视频地址：" prop="VideoPath">
              <el-input v-model="form.VideoPath"></el-input>
          </el-form-item>
      </el-col>
      <el-col :span="20" v-if="$route.query.type==1">
          <el-form-item label="课程收获：" prop="Gain">
              <el-input type="textarea" v-model="form.Gain"></el-input>
          </el-form-item>
      </el-col>
      <el-col :span="20">
          <el-form-item>
              <el-button size="medium" type="primary" @click="save">保存</el-button>
          </el-form-item>
      </el-col>
    </el-form>
    <div v-if="$route.query.id">
        <!-- 关联视频 关联考试 -->
        <associated-video-test :videoid="$route.query.id" v-if="$route.query.type==1"></associated-video-test>
        
        <div class="row page-title">
            <div class="col-xs-11">
                <h1>欢迎程度</h1>
            </div>
        </div>
        <el-form label-width="150px">
            <el-col :span="8">
                <el-form-item label="浏览人数：">
                    <div style="width:70%;">{{WelcomeForm.PeopleNum}}</div>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="浏览人次：">
                    <div style="width:70%;">{{WelcomeForm.PersonTime}}</div>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="点赞次数：">
                    <div style="width:70%;">{{WelcomeForm.PraiseTime}}</div>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="收藏次数：">
                    <div style="width:70%;">{{WelcomeForm.CollectTime}}</div>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="分享次数：">
                    <div style="width:70%;">{{WelcomeForm.ShareTime}}</div>
                </el-form-item>
            </el-col>
        </el-form>
        <div class="row page-title">
            <div class="col-xs-11">
                <h1>评论信息</h1>
            </div>
        </div>
        <el-col :span="24" class="table-bottom-margin">
            <el-table :data="reviewTable" border style="width: 100%" :header-cell-class-name="headerbg">
                <el-table-column prop="UserName" label="评论人"></el-table-column>
                <el-table-column prop="CommentContent" label="评论内容"> </el-table-column>
                <el-table-column prop="State" label="状态"> </el-table-column>
                <el-table-column prop="AddTime" label="评论时间" :formatter="DateFormatter"> </el-table-column>
                <el-table-column label="操作" align="center" min-width="40" width="250px">
                    <template slot-scope="scope">
                        <el-tooltip content="删除" placement="top">
                            <i class="fa fa-trash el-text-danger" @click="del(scope.row.Id)"></i>
                        </el-tooltip>&nbsp;&nbsp;&nbsp;&nbsp;   
                        <el-tooltip placement="top">
                            <div slot="content">{{scope.row.State=='审核通过'?'不通过':'通过'}}</div>
                            <i :class="{'fa fa-ban el-text-danger':scope.row.State=='审核通过','glyphicon glyphicon-ok-circle el-text-success':scope.row.State=='等待审核'}" @click="updateState(scope.row)"></i>
                        </el-tooltip>         
                    </template>
                </el-table-column>
            </el-table>    
        </el-col>
        <el-col :sapn="24" style="text-align:right" v-if="count>0">
            <el-pagination @size-change="pageSizeChange" @current-change="pageCurrentChange" :current-page="currentPage"
                :page-sizes="[10]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="count">
            </el-pagination>
        </el-col>
        <div class="row page-title">
            <div class="col-xs-11">
                <h1>评价信息</h1>
            </div>
        </div>
        <el-col :span="24" class="table-bottom-margin">
            <el-table :data="evaluativeInforTable" border style="width: 100%" :header-cell-class-name="headerbg">
                <el-table-column prop="UserName" label="评价人"></el-table-column>
                <el-table-column prop="WholeMark" label="整体打分"> </el-table-column>
                <el-table-column prop="ContentMark" label="内容实用性"> </el-table-column>
                <el-table-column prop="TaughtMark" label="老师的讲解"> </el-table-column>
                <el-table-column prop="EvaluateLable" label="课程标签"> </el-table-column>
                <el-table-column prop="EvaluateContent" label="评语"> </el-table-column>
                <el-table-column prop="AddTime" label="评价时间" :formatter="DateFormatter"> </el-table-column>
            </el-table>    
        </el-col>
        <el-col :sapn="24" style="text-align:right" v-if="count>0">
            <el-pagination @size-change="pageSizeChangeEvaluative" @current-change="pageCurrentChangeEvaluative" :current-page="currentPageEvaluativeInfor"
                :page-sizes="[10]" :page-size="pageSizeEvaluativeInfor" layout="total, sizes, prev, pager, next, jumper" :total="countEvaluativeInfor">
            </el-pagination>
        </el-col>
        <div class="row page-title">
            <div class="col-xs-11">
                <h1>购买记录</h1>
            </div>
        </div>
        <el-col :span="24" class="table-bottom-margin">
            <el-table :data="purchaseHistoryTable" border style="width: 100%" :header-cell-class-name="headerbg">
                <el-table-column prop="UserName" label="购买人"></el-table-column>
                <el-table-column prop="AddTime" label="购买时间"> </el-table-column>
                <el-table-column prop="GoldNum" label="金额"> </el-table-column>
                <el-table-column prop="Id" label="流水号码"> </el-table-column>
            </el-table>    
        </el-col>
        <el-col :sapn="24" style="text-align:right" v-if="count>0">
            <el-pagination @size-change="pageSizeChangePurchase" @current-change="pageCurrentChangePurchase" :current-page="currentPagePurchaseHistory"
                :page-sizes="[10]" :page-size="pageSizePurchaseHistory" layout="total, sizes, prev, pager, next, jumper" :total="countPurchaseHistory">
            </el-pagination>
        </el-col>
    </div>
  </div>
</template>

<script>
import AssociatedVideoTest from './AssociatedVideoTest.vue';
export default {
  data(){
    return{
        user:JSON.parse( sessionStorage.getItem('user')),
        headerbg:'headerbg',//表格头部背景色
        getEvaluativeInforListUrl:this.urlConfig+'/api/VideoManage/GetEvaluateinfoList',//获取评价信息table
        getPurchaseHistoryListUrl:this.urlConfig+'/api/VideoManage/GetUserbuyrecordList',//获取购买记录table

        getListUrl:this.urlConfig+'/api/VideoManage/GetCommentinfoList',//获取评论信息table
        delUrl:this.urlConfig+'/api/VideoManage/PostDeleteCommentinfo',//删除评论信息
        updateStateUrl:this.urlConfig+'/api/VideoManage/PostEditCommentinfo',//修改评论信息状态

        addUrl:this.urlConfig+'/api/VideoManage/VideoAdd',//添加单视频
        editUrl:this.urlConfig+'/api/VideoManage/VideoUpdate',//编辑单视频
        detailUrl:this.urlConfig+'/api/VideoManage/GetVideoById',//获取详情单视频

        DropDownListUrl:this.urlConfig+'/api/VideoManage/GetExpertComboxList',//下拉列表
        uploadUrl:this.urlConfig+'/api/AdvertInfo/PostImgUpload/',//上传图片接口
        
        reviewTable:[],//评论信息table
        currentPage:1,
        pageSize:10,
        count:0,
        evaluativeInforTable:[],//评价信息table
        currentPageEvaluativeInfor:1,
        pageSizeEvaluativeInfor:10,
        countEvaluativeInfor:0,
        purchaseHistoryTable:[],//购买记录table
        currentPagePurchaseHistory:1,
        pageSizePurchaseHistory:10,
        countPurchaseHistory:0,
        form:{},//单视频
        WelcomeForm:{},//欢迎程度
        rules:{//单视频验证
            Title:[
                { required: true, message: '请输入标题', trigger: 'blur' },
            ],
            Diction:[
                { required: true, message: '请输入描述', trigger: 'blur' },
            ],
            GoldPrice:[
                { required: true, message: '请输入金币价格', trigger: 'blur' },
            ],
            ExpertId:[
                { required: true, message: '请选择主讲专家', trigger: 'change' },
            ],
            // VideoPath:[
            //     { required: true, message: '请输入视频地址', trigger: 'blur' },
            // ]
        },
        searchedSelectList: [],//主讲专家下拉列表
        dropDownList: [],
        loading: false,//end主讲专家下拉列表
        
        imageUrl: '',//上传图片
    }
  },
  components:{
      AssociatedVideoTest
  },
  watch: {
    //   form(curVal, oldVal) {
    //       console.log('new',curVal,'old:',oldVal);
    //   }
  },
  computed:{
      
  },
  mounted() {
    this.getDropDownList();
    this.getDetail();
    this.getList(10,this.currentPage);//获取评论信息table
    this.getEvaluativeInforList(10,this.currentPageEvaluativeInfor);//获取评价信息table
    this.getPurchaseHistoryList(10,this.currentPagePurchaseHistory);//获取购买记录table
  },
  methods:{
    DateFormatter:function(row){
        return (!row.AddTime)?'':moment(row.AddTime).format("YYYY-MM-DD HH:mm");
    },
    handleAvatarSuccess(res, file) {//img
        if(res["Code"] == "200") {
            this.form.ShowImage = this.urlConfig+res.ImgUrl;
        }
        this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
    },//img
    remoteMethod(query) {//搜索下拉列表select 搜索触发
        if (query !== '') {
            this.loading = true;
            setTimeout(() => {
                this.loading = false;
                this.searchedSelectList = this.dropDownList.filter(item => {
                    return item.ExpertName.indexOf(query) > -1;
                });
            }, 200);
        } else {
            this.searchedSelectList = [];
        }
    },
    getDropDownList:function(){
        this.$http.get(this.DropDownListUrl,{
            emulateJSON:true
        }).then(function(res){
            if(res.body["Code"] == "200") {
                this.dropDownList = JSON.parse(res.body.Data);
                this.searchedSelectList = this.dropDownList;
            }
        });
    },
    getDetail(){//获取视频详情
        this.form={};
        this.WelcomeForm={};
        if(this.$route.query.id){
            this.$http.get(this.detailUrl+'?Id='+this.$route.query.id+'&VideoType='+this.$route.query.type).then(function(res){
                if(res.body["Code"] == "200") {
                    var result= JSON.parse(res.body.Data);
                    this.WelcomeForm ={
                        PeopleNum:result.PeopleNum,
                        PersonTime:result.PersonTime,
                        PraiseTime:result.PraiseTime,
                        CollectTime:result.CollectTime,
                        ShareTime:result.ShareTime
                    };
                    // this.form = result;
                    this.form={
                        Id:result.Id,
                        Title:result.Title,
                        Diction:result.Diction,
                        GoldPrice:result.GoldPrice,
                        ExpertId:result.ExpertId,
                        VideoPath:result.VideoPath,//视频地址
                        Gain:result.Gain
                    };
                }
            });
        }
    },
    validateFun:function(){//验证单视频表单
        var errorInfo='';
        // ['Title','Diction','GoldPrice','ExpertId','VideoPath']
        var validateArr = ['Title','Diction','GoldPrice','ExpertId'];
        for(var i=0;i<validateArr.length;i++){
            this.$refs.form.validateField((validateArr[i]),(re)=>{
                errorInfo+=re+(re==''?'':', ');
            })
        }
        return errorInfo;
    },
    save:function(){//edit add单视频表单
        var saveUrl = this.addUrl;
        if(this.$route.query.id){//edit
            saveUrl = this.editUrl;
            this.form.Id = this.$route.query.id;
        }
        var errorInfo=this.validateFun();
        if(!errorInfo){
            this.$http.post(saveUrl,this.form,{
                emulateJSON: true
            }).then(function(res) {
                if(res.body["Code"] == "200") {
                    this.$notify({title: '成功',message: '保存成功！',type: 'success'});
                    if(this.$route.query.id){//edit
                        this.getDetail();
                    }else{//add
                        if(this.$route.query.type==1){//多视频跳转
                            this.$router.push({ path: '/Video/MultiVideo' });
                        }else{//单视频跳转
                            this.$router.push({ path: '/Video/SingleVideo' });
                        }
                    }
                }else{
                    this.$notify.error({title: '错误',message:res.body["Message"]});
                }
            });
        }else{
            this.$notify({title: '警告',message: errorInfo,type: 'warning',duration:1200});
            return false;
        }
    },
    getList:function(PageSize,PageIndex){//获取评论信息table
        this.$http.get(this.getListUrl+'?PageSize='+PageSize+'&PageNo='+PageIndex+'&VideoId='+this.$route.query.id,{
            emulateJSON:true
        }).then(function(res){
            if(res.body["Code"] == "200") {
                this.count = res.body.Count;
                this.reviewTable = JSON.parse(res.body.Data);
            }
        });
    },
    getEvaluativeInforList(PageSize,PageIndex){//获取评价信息table
        this.$http.get(this.getEvaluativeInforListUrl+'?PageSize='+PageSize+'&PageNo='+PageIndex+'&VideoId='+this.$route.query.id,{
            emulateJSON:true
        }).then(function(res){
            if(res.body["Code"] == "200") {
                this.countEvaluativeInfor = res.body.Count;
                this.evaluativeInforTable = JSON.parse(res.body.Data);
            }
        });
    },
    getPurchaseHistoryList(PageSize,PageIndex){//获取购买记录table
        this.$http.get(this.getPurchaseHistoryListUrl+'?PageSize='+PageSize+'&PageNo='+PageIndex+'&VideoId='+this.$route.query.id,{
            emulateJSON:true
        }).then(function(res){
            if(res.body["Code"] == "200") {
                this.countPurchaseHistory = res.body.Count;
                this.purchaseHistoryTable = JSON.parse(res.body.Data);
            }
        });
    },
    del:function(id){//删除评论信息
        this.$confirm('确定需要删除该记录?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            this.$http.post(this.delUrl+'?Id='+id+'&VideoId='+this.$route.query.id,{},{
                emulateJSON:true
            }).then(function(res){
                if(res.body["Code"] == "200") {
                    this.getList(10,this.currentPage);
                    this.$notify({title: '成功',message: '删除成功！',type: 'success'});
                }else{
                    this.$notify({title: '警告',message: res.body["Message"],type: 'warning',duration:1200});
                }
            });
        }).catch(() => {});
    },
    updateState:function(row){//修改评论信息状态
        this.$http.post(this.updateStateUrl+'?Id='+row.Id+'&LoginId='+this.user.Id+'&VideoId='+this.$route.query.id+'&CommentStatus='+(row.State=='审核通过'?false:true),{},{
            emulateJSON: true
        }).then(function(res) {
            if(res.body["Code"] == "200") {
                this.getList(10,this.currentPage);
            }else{
                this.$notify.error({title: '错误',message:res.body["Message"]});
            }
        });
    },
    pageSizeChange:function(val){//评论信息
        this.pageSize = val;
        this.getList(val,this.currentPage);
    },
    pageCurrentChange:function(val){//评论信息
        this.currentPage = val;
        this.getList(this.pageSize,val);
    },
    pageSizeChangeEvaluative:function(val){//评价信息
        this.pageSizeEvaluativeInfor = val;
        this.getEvaluativeInforList(val,this.currentPageEvaluativeInfor);
    },
    pageCurrentChangeEvaluative:function(val){//评价信息
        this.currentPageEvaluativeInfor = val;
        this.getEvaluativeInforList(this.pageSizeEvaluativeInfor,val);
    },
    pageSizeChangePurchase:function(val){//购买记录
        this.pageSizePurchaseHistory = val;
        this.getPurchaseHistoryList(val,this.currentPagePurchaseHistory);
    },
    pageCurrentChangePurchase:function(val){//购买记录
        this.currentPagePurchaseHistory = val;
        this.getPurchaseHistoryList(this.pageSizePurchaseHistory,val);
    }
  }
}
</script>
